package cac.fenjian.resource.dispatchSearch.service;

import cac.common.CallInterFace.service.CallInterfaceService;
import cac.common.CreatMsgId;
import cac.fenjian.resource.AoTask.MsAoMatchInfo.dao.MsAoMatchInfoDao;
import cac.fenjian.resource.dispatchSearch.dao.MsDeliveryPackageInfoDao;
import cac.gkinterface.service.WorkService;
import com.alibaba.fastjson.JSONObject;
import com.cac.dme.adapter.rest.msg.ResponseMsg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class MsDeliveryPackageInfoService {

    @Autowired
    private MsDeliveryPackageInfoDao msDeliveryPackageInfoDao;

    @Autowired
    private MsAoMatchInfoDao msAoMatchInfoDao;

    @Autowired
    private CallInterfaceService callInterfaceService;

    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private Environment environment;

    @Autowired
    private WorkService workService;


    //配送物料查询信息
    public PageInfo deliveryMaterial(int startPage, int pageSize, HashMap queryParam) {
        PageHelper.startPage(startPage, pageSize);
        List<HashMap> data = msDeliveryPackageInfoDao.deliveryMaterial(queryParam);
        PageInfo pageInfo = new PageInfo(data);
        return pageInfo;
    }
    public PageInfo waitingDispatch(int startPage, int pageSize, HashMap queryParam) {
        PageHelper.startPage(startPage, pageSize);
        List<HashMap> data = msDeliveryPackageInfoDao.waitingDispatch(queryParam);
        PageInfo pageInfo = new PageInfo(data);
        return pageInfo;
    }

    public List<HashMap> queryNoDaliyTimeAoByCarCode(HashMap map){
        return msDeliveryPackageInfoDao.queryNoDaliyTimeAoByCarCode(map);
    }

    public List<HashMap> querySendMaterial(HashMap map){
        return msDeliveryPackageInfoDao.querySendMaterial(map);
    }

    //查询小车组号
    public String getCarGroupCode(String carCode){
        return msDeliveryPackageInfoDao.getCarGroupCode(carCode);
    }


    public boolean queryPackageExistsDaliyPlan(String carCode){
       int c = msDeliveryPackageInfoDao.queryPackageExistsDaliyPlan(carCode);
       if(c>0){
           return true;
       }else{
           return false;
       }
    }
    public  String queryAoExistsDaliy(String carCode){
        return msDeliveryPackageInfoDao.queryAoNotExistsDaily(carCode);
    }
    public boolean existsRepeatDelivery(String groupCode){
        msDeliveryPackageInfoDao.clearDeliveryRepeatCheck(groupCode);
        msDeliveryPackageInfoDao.insertDeliveryRepeat(groupCode);
        int cnt = msDeliveryPackageInfoDao.queryRepeatCnt(groupCode);
        if(cnt==0){
            return false;
        }else{
            return true;
        }
    }

    public HashMap checkSendQty(String groupCode){
        HashMap ret = new HashMap();
        ret.put("retCode","200");
        StringBuilder sb = new StringBuilder();
        List<HashMap> billList = msDeliveryPackageInfoDao.querySendBillId(groupCode);
        for(HashMap billInfo : billList){
            List<HashMap> list = msDeliveryPackageInfoDao.checkBillQtyAndPackageQty(billInfo.get("msAoMatchBillId").toString());
            for(HashMap tmp : list){
                sb.append(tmp.get("aoCode"))
                        .append(",图号为：")
                        .append(tmp.get("itemCode"))
                        .append("需求数量不对，实际需求数量：")
                        .append(tmp.get("itemQty"))
                        .append("，实际配送数量：")
                        .append(tmp.get("packageCount"));
                ret.put("retCode","201");
            }
        }
        ret.put("retMsg",sb.toString());
        return ret;
    }

    //更新小车配送状态
    public int updateWorkbinCar(String carCode){
        return msDeliveryPackageInfoDao.updateWorkbinCar(carCode);
    }

    public int updateWorkbinCarByDeliveryPlanId(String wmsDeliveryPlanId,String groupCode){
        return msDeliveryPackageInfoDao.updateWorkbinCarByDeliveryPlanId(wmsDeliveryPlanId,groupCode);
    }

    public int udpateDeliveryGroupCode(String wmsDeliveryPlanId,String groupCode){
        return msDeliveryPackageInfoDao.udpateDeliveryGroupCode(wmsDeliveryPlanId,groupCode);
    }

    //绑定小车编码和托盘编码 分拣出库回传erp
    public ResponseMsg deliveryPackage(String carCode, List<String> toolCodes, String groupCode) {
        ResponseMsg responseMsg = new ResponseMsg();
        responseMsg.setMessage("装车成功！");
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String opUserCode = (String) request.getSession().getAttribute("account");
        String result = null;
        HashMap map = new HashMap();
        map.put("carCode", carCode);
        map.put("groupCode", groupCode);
        map.put("outInt", null);
        map.put("outString", null);
        try {
            for (String toolCode : toolCodes) {
                map.put("toolCode", toolCode);
                //yebo 2023-08-08 新增判断 当前托盘是否已经装车
                int c = msDeliveryPackageInfoDao.queryToolIsOnCar(toolCode,carCode);
                if(c>0){ //yebo已经装车的托盘不重新执行下面操作
                    responseMsg.setMessage(responseMsg.getMessage()+";"+toolCode+"托盘已经装车");
                    continue;
                }

                //新增小车绑定物料工作器具包id
                msDeliveryPackageInfoDao.callCarCodeBle(map);

//                log.info("-------------------配送交接创建结果: " + map.get("o_return_string").toString() + "outint" + map.get("o_return_int").toString());
                //查询占用id、台账id
                List<HashMap> outId = msDeliveryPackageInfoDao.sortingInvOut(toolCode);
                //2023-07-10lqc
                //更新占用表占用状态
                for (HashMap hashMap : outId) {
                    msDeliveryPackageInfoDao.updateAllotment(hashMap);
                }
                //修改matchInfo配送状态
                msDeliveryPackageInfoDao.updateMatchInfo(toolCode, opUserCode, IP);
                //判断当前ao下物料是否全部配送
                HashMap ao = msDeliveryPackageInfoDao.selectAoDeliveryState(toolCode);
                if (!Objects.isNull(ao)) {//不为空，当前ao已经全部配送，修改ao状态为全部配送
                    msDeliveryPackageInfoDao.updateTaskAoAll(ao);
                    //修改工作包配送状态为全部
                    int cnt = msDeliveryPackageInfoDao.updatePackageAll(ao);
                    if (cnt == 0) {
                        //修改工作包配送状态为部分
                        msDeliveryPackageInfoDao.updatePackagePart(ao);
                    }
                } else {//修改ao状态为部分配送
                    msDeliveryPackageInfoDao.updateTaskAoPart(toolCode);
                }
                //修改workbin配送状态
                msDeliveryPackageInfoDao.updateWorkBin(toolCode);
            }

            //全部成功提交事务
            platformTransactionManager.commit(transaction);
            responseMsg.setRetCode("200");
        } catch (Exception e) {
            //有一个失败，回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(transaction);
            e.printStackTrace();
            responseMsg.setRetCode("201");
            responseMsg.setMessage("装车失败");
        } finally {
            return responseMsg;
        }
    }

//    //查询已配套工作包ao信息
//    public QueryRespBean<List<HashMap>> searchPackageAo(QueryReqBean<List<HashMap>> queryReqBean) {
//        QueryRespBean<List<HashMap>> queryRespBean = new QueryRespBean<>();
//        try {
//            PageHelper.startPage(queryReqBean.getPageParameter());
//            Page<List<HashMap>> dataList = msDeliveryPackageInfoDao.searchPackageAo();
//            queryRespBean.setResult(dataList);
//            return queryRespBean;
//        } catch (Exception e) {
//            throw new DaoException(e.getMessage());
//        }
//    }

    //查询工作包下托盘信息
    public HashMap selectByPackageCode(String packageCode) {
        return msDeliveryPackageInfoDao.selectByPackageCode(packageCode);
    }

    //查询配送任务数量信息
    public HashMap countSearch(String time) {
        HashMap result = msDeliveryPackageInfoDao.countSearch(time);
        return result;
    }

    //定时上传配套状态
    public String dateDeliveryStatus() {
        List<HashMap> dateStatus = msDeliveryPackageInfoDao.dateDeliveryStatus();
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            for (int i = 0; i < dateStatus.size(); i++) {
                HashMap invOut = dateStatus.get(i);
                String msgId = CreatMsgId.getMsgId();
                //组装BData
                JSONObject funcJson = new JSONObject(invOut);
                JSONObject resultOb = new JSONObject();
                resultOb.put("data", funcJson);
                resultOb.put("func", "101-MES-MaterialState");
                resultOb.put("msgId", msgId);
                final Base64.Encoder encoder = Base64.getEncoder();
                String parameters = encoder.encodeToString(resultOb.toJSONString().getBytes());
                log.info("============================工控网上传_配送状态==========================");
                String code = "sendBData";
                String sendScenario = "配送状态";
                String name = "两网传输-发送业务数据";
                long beginTime = System.currentTimeMillis();
                log.info("======开始时间=======" + beginTime);
                callInterfaceService.sendBData(code, name, parameters, sendScenario);
                long endTime = System.currentTimeMillis();
                log.info("======消耗时间=======" + (endTime - beginTime) + "ms");
                log.info("============================工控网上传_配送状态==========================");
                //工控网上传数据
                HashMap issuedTest = new HashMap();
                issuedTest.put("BData", resultOb.toJSONString());
                issuedTest.put("type", resultOb.get("func"));
                issuedTest.put("msgId", msgId);
                workService.issuedTest(issuedTest);
                log.info("工控网上传程序后台日志:>>>>>>>>>>>>>>>>>>>>>>>>>issuedParameters:" + issuedTest.toString());
            }
            //全部成功提交事务
            platformTransactionManager.commit(transaction);
            return "200";
        } catch (Exception e) {
            //有一个失败，回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(transaction);
            e.printStackTrace();
            return "201";
        }
    }

    public ResponseMsg createDelivery(List<HashMap> list,String groupCode,String opUserCode,String IP){
        ResponseMsg responseMsg = new ResponseMsg();
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        for(HashMap map : list){
            //判断物料是否装车
            List<String> deliveryPlanIds = msDeliveryPackageInfoDao.selectMaterialIsOnCar(map);
            if(deliveryPlanIds.size()>1){
                platformTransactionManager.rollback(transaction);
                return responseMsg.setRetCode("201").setMessage("装车交接单有重复数据！");
            }else if(deliveryPlanIds.size()==1){
                String wmsDeliveryPlanId = deliveryPlanIds.get(0);
                //更新原来交接单组号
                msDeliveryPackageInfoDao.udpateDeliveryGroupCode(wmsDeliveryPlanId,groupCode);
                //更新原来小车的组号
                msDeliveryPackageInfoDao.updateOnCarByDeliveryPlanId(wmsDeliveryPlanId,groupCode);
            }else{
                //生成交接单
                HashMap callMap = new HashMap();
                String toolCode = "L-D-00000019";
                callMap.put("carCode", toolCode);
                callMap.put("groupCode", groupCode);
                callMap.put("outInt", null);
                callMap.put("outString", null);
                msDeliveryPackageInfoDao.callCarCodeBle(callMap);
                List<HashMap> outId = msDeliveryPackageInfoDao.sortingInvOut(toolCode);
                //2023-07-10lqc
                //更新占用表占用状态
                for (HashMap hashMap : outId) {
                    msDeliveryPackageInfoDao.updateAllotment(hashMap);
                }
                //修改matchInfo配送状态
                msDeliveryPackageInfoDao.updateMatchInfo(toolCode, opUserCode, IP);
                //判断当前ao下物料是否全部配送
                HashMap ao = msDeliveryPackageInfoDao.selectAoDeliveryState(toolCode);
                if (!Objects.isNull(ao)) {//不为空，当前ao已经全部配送，修改ao状态为全部配送
                    msDeliveryPackageInfoDao.updateTaskAoAll(ao);
                    //修改工作包配送状态为全部
                    int cnt = msDeliveryPackageInfoDao.updatePackageAll(ao);
                    if (cnt == 0) {
                        //修改工作包配送状态为部分
                        msDeliveryPackageInfoDao.updatePackagePart(ao);
                    }
                } else {//修改ao状态为部分配送
                    msDeliveryPackageInfoDao.updateTaskAoPart(toolCode);
                }
                //修改workbin配送状态
                msDeliveryPackageInfoDao.updateWorkBin(toolCode);
            }

        }
        platformTransactionManager.commit(transaction);
        return responseMsg.setRetCode("200").setMessage("操作成功");
    }
}
